<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert
        show-icon
        :closable= 'false'
        title="只允许选中三级分类"
        type="warning">
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="row-margin">
          <el-col>
              <span>选择商品分类:</span>
            <el-cascader
              clearable
              v-model="selectedKeys"
              :options="cateList"
              :props= "cascaderProps"
              @change="cascaderCateChange"></el-cascader></el-col>
      </el-row>
      <!-- tab页签区 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
            <el-button type='primary' size='mini' :disabled='isDisabled' @click="addDialogVisible = true">添加参数</el-button>
            <!-- 动态数据表格 -->
            <el-table :data='manyTableData' border stripe>
              <el-table-column type='expand' >
                <template slot-scope="scope">
                  <el-tag v-for="(item, index) in scope.row.attr_vals" closable :key="index" @close="tagClose(index, scope.row)">{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type='index' label="#"></el-table-column>
              <el-table-column prop='attr_name' label="参数名称"></el-table-column>
              <el-table-column label='操作'>
                <template slot-scope="scope">
                  <!-- <pre>{{scope.row}}</pre> -->
                  <el-button type='primary' size='mini' icon='el-icon-edit' @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type='pdanger' size='mini' icon='el-icon-delete' @click="removeParams(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
            <el-button type='primary' size='mini' :disabled='isDisabled' @click="addDialogVisible = true">添加属性</el-button>
            <!-- 静态数据表格 -->
            <el-table :data='onlyTableData' border stripe>
              <el-table-column type='expand' >
                <template slot-scope="scope">
                  <el-tag v-for="(item, index) in scope.row.attr_vals" closable :key="index" @close="tagClose(index, scope.row)">{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type='index' label="#"></el-table-column>
              <el-table-column prop='attr_name' label="属性名称"></el-table-column>
              <el-table-column label='操作'>
                <template slot-scope="scope">
                  <el-button type='primary' size='mini' icon='el-icon-edit' @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type='pdanger' size='mini' icon='el-icon-delete' @click="removeParams(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框  动态参数/静态属性 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="30%"
      @close='addDialogClose()'>
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框  动态参数/静态属性 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="30%"
      @close='editDialogClose()'>
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 数据列表
      cateList: [],
      // 级联选择框选中的数据 表现为ID
      selectedKeys: [],
      // 级联选择框配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // tab页签区默认显示的页签名称
      activeName: 'many',
      // 静态参数数据
      onlyTableData: [],
      // 动态参数数据
      manyTableData: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '必填参数名', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        attr_name: [
          { required: true, message: '必填参数名', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 获取所有商品分类数据
    this.getCateList()
  },
  computed: {
    isDisabled () {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    // 拿到请求参数列表的id 分类id
    isId () {
      if (this.selectedKeys.length === 3) {
        // 返回最后一项的ID数据
        return this.selectedKeys[2]
      }
      return null
    },
    // 动态计算标题对话框
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  methods: {
    // 获取所有商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取所有商品分类数据失败!')
      }
      this.cateList = res.data
    //   console.log(this.cateList)
    },
    // 级联框改变
    cascaderCateChange () {
      this.getParamsData()
    },
    // tab页签点击事件函数
    handleTabClick () {
      this.getParamsData()
      console.log(this.activeName)
    },
    // 参数列表数据获取
    async getParamsData () {
      // 选中的不是三级分类
      if (this.selectedKeys.length !== 3) {
        // 级联框清空
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 选中的是三级分类
      console.log(this.selectedKeys)
      const { data: res } = await this.$http.get(`categories/${this.isId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      // 把attr_vals字符串转换成数组
      res.data.forEach(item => {
        // 如果attr_vals是空字符串 返回false空数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加参数
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.isId}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    async showEditDialog (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`categories/${this.isId}/attributes/${id}`, {
        params: {
          attr_sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.editForm = res.data
      console.log(this.editForm)
    },
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑确认按钮
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起请求
        const { data: res } = await this.$http.put(`categories/${this.isId}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        console.log(res.meta)
        this.$message.success('修改成功')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 删除对话框
    removeParams (id) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.isId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getParamsData()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // tag标签失去焦点或者按下enter
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.updataTag(row)
    },
    async updataTag (row) {
      const { data: res } = await this.$http.put(`categories/${this.isId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        // 把数组再改回字符串
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新tag失败')
      this.$message.success('更新tag成功')
    },
    // tag标签输入框显示
    showInput (row) {
      row.inputVisible = true
      // 自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除tag
    tagClose (index, row) {
      row.attr_vals.splice(index, 1)
      this.updataTag(row)
    }
  }
}
</script>
<style lang="less" scoped>
.row-margin {
   margin: 10px 0;
}
.el-tag {
  margin: 8px;
}
.input-new-tag {
  width: 90px;
}
</style>
